<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Attendance and Absence Chart</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
 <style>
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  background-color: #f4f4f4;
}

.navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
.navbar a:hover {
  background-color: #ddd;
  color: black;
}
.chart-container {
  width: 46%; /* 每个图表占页面宽度的 46% */
  height: 500px; /* 图表高度为 400px */
  margin: 1.5%; /* 图表间距 */
  display: inline-block; /* 使用 inline-block 排列图表 */
  box-sizing: border-box; /* 包括 padding 和 border 在宽高中 */
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
canvas {
  width: 100%; /* 确保 canvas 占满容器宽度 */
  height: 100%; /* 确保 canvas 占满容器高度 */
}
h3 {
  font-family: Arial, sans-serif;
  font-size: 16px;
  margin-bottom: 5px;
  text-align: center;
  background-color: #f2f2f2;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}
#charts-container {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.dynamic-chart-container h3 {
  width: 100%;
  background-color: #f2f2f2;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}
.dynamic-chart-container canvas {
  width: 100%;
  height: 100%;
}
</style>
</head>
</body>


<!-- 固定图表容器 -->
<div class="chart-container">
  <h3>货品上架下架数量</h3>
  <canvas id="data1_Chart"></canvas>
</div>
<div class="chart-container">
  <h3>各个商品号的数量</h3>
  <canvas id="data2_Chart"></canvas>
</div>
<div class="chart-container">
  <h3>各个物品数量</h3>
  <canvas id="data3_Chart"></canvas>
</div>
<div class="chart-container">
  <h3>各个货品号上架下架的数量</h3>
  <canvas id="data4_Chart"></canvas>
</div>

<!-- 动态图表容器 -->
<div id="charts-container"></div>

<script>

   const ctx = document.getElementById('data1_Chart').getContext('2d');
        const dynamicChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [], // 用于存放时间相关标签，后续可根据实际情况设置具体时间值
                datasets: [
                    {
                        label: '上架',
                        data: [],
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 2,
                        tension: 0.3, // Smooth the line
                        fill: false
                    },
                    {
                        label: '下架',
                        data: [],
                        borderColor: 'rgba(255, 99, 132, 1)',
                        borderWidth: 2,
                        tension: 0.3,
                        fill: false
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: true
                    }
                },
                scales: {
                    x: {
                        title: {
                            display: true,
                            text: '时间' // 将横坐标标题改为时间
                        },
                        ticks: {
                            display: true // 显示X轴刻度，方便查看时间
                        }
                    },
                    y: {
                        title: {
                            display: true,
                            text: '数量'
                        },
                        ticks: {
                            min: 0, // 设置y轴最小值为0
                            max: 5, // 修改此处，将y轴最大值设置为5
                            stepSize: 1 // 可以根据需要调整刻度步长，这里设为1方便查看
                        }
                    }
                }
            }
        });

        async function updateChartData1() {
            try {
                const response = await fetch('http://127.0.0.1:5000/get_data1');
                const data = await response.json();
                console.log(data)
                const timeStamp = new Date().toLocaleTimeString(); // 获取当前时间作为时间标签，可根据实际需求调整获取时间的方式
                dynamicChart.data.labels.push(timeStamp);

                const upData = [];
                const downData = [];
                for (const item of data) {
                    if (item.operation === '上架') {
                        upData.push(item.quantity);
                    } else if (item.operation === '下架') {
                        downData.push(item.quantity);
                    }
                }

                dynamicChart.data.datasets[0].data.push(upData.length > 0? upData[0] : 0);
                dynamicChart.data.datasets[1].data.push(downData.length > 0? downData[0] : 0);

                if (dynamicChart.data.labels.length > 5) {
                    dynamicChart.data.labels.shift();
                    dynamicChart.data.datasets[0].data.shift();
                    dynamicChart.data.datasets[1].data.shift();
                }
                dynamicChart.update();
            } catch (error) {
                console.error('Error fetching or updating chart data:', error);
            }
        }

        setInterval(updateChartData1, 5000);
        updateChartData1();


    //----------------------2.data2-----------------------
   const barCtx = document.getElementById('data2_Chart').getContext('2d');
        const AAAChart = new Chart(barCtx, {
            type: 'bar',
            data: {
                labels: ['1000000', '1000001', '1000002', '1000003', '1000004', '1000005', '1000006', '1000007', '1000008', '1000009'],
                datasets: [
                    {
                        label: 'Product Quantity',
                        data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],  // 初始化为10个0，对应10个横坐标
                        backgroundColor: 'rgba(75, 192, 192, 0.5)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: true
                    }
                },
                scales: {
                    x: {
                        title: {
                            display: true,
                            text: '货品号'
                        }
                    },
                    y: {
                        title: {
                            display: true,
                            text: '数量'
                        },
                        ticks: {
                            min: 1,  // 设置y轴最小值为1
                            max: 5   // 设置y轴最大值为5
                        }
                    }
                }
            }
        });

        async function updateChartData2() {
            try {
                const response = await fetch('http://127.0.0.1:5000/get_data2');  // 假设后端接口获取对应数据
                const data = await response.json();
                const quantityValues = AAAChart.data.datasets[0].data.slice();  // 获取原有的数量数据

                data.forEach(item => {
                    const productIndex = AAAChart.data.labels.indexOf(item.productId.toString());  // 找到对应横坐标索引
                    if (productIndex!== -1) {
                        quantityValues[productIndex] = item.quantity;
                    }
                });

                AAAChart.data.datasets[0].data = quantityValues;
                AAAChart.update();
            } catch (error) {
                console.error('Error fetching or updating chart data:', error);
            }
        }

        setInterval(updateChartData2, 5000);
        updateChartData2();


    //----------------------3.data3_Chart-----------------------
        const courseCtx = document.getElementById('data3_Chart').getContext('2d');
        const courseChart = new Chart(courseCtx, {
            type: 'bar',
            data: {
                labels: ['product1', 'product2', 'product3', 'product4', 'product5', 'product6', 'product7', 'product8', 'product9'],
                datasets: [
                    {
                        label: 'Product Quantity',
                        data: [0, 0, 0, 0, 0, 0, 0, 0, 0],
                        backgroundColor: 'rgba(153, 102, 255, 0.5)',
                        borderColor: 'rgba(153, 102, 255, 1)',
                        borderWidth: 1
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: true
                    }
                },
                scales: {
                    x: {
                        title: {
                            display: true,
                            text: '物品'
                        }
                    },
                    y: {
                        title: {
                            display: true,
                            text: '数量'
                        },
                        ticks: {
                            min: 1,
                            max: 5
                        }
                    }
                }
            }
        });

        async function updateChartData3() {
            try {
                const response = await fetch('http://localhost:5000/get_data3');
                const data = await response.json();
                const quantityValues = courseChart.data.datasets[0].data.slice();

                data.forEach(item => {
                    const productIndex = courseChart.data.labels.indexOf(item.productId);
                    if (productIndex!== -1 && item.quantity >= 1 && item.quantity <= 5) {
                        quantityValues[productIndex] = item.quantity;
                    }
                });

                courseChart.data.datasets[0].data = quantityValues;
                courseChart.update();
            } catch (error) {
                console.error('Error fetching or updating chart data:', error);
            }
        }

        setInterval(updateChartData3, 5000);
        updateChartData3();

    // ----------------------4.courseAttendance----------------

    const courseAttendanceCtx = document.getElementById('data4_Chart').getContext('2d');
        const courseAttendanceChart = new Chart(courseAttendanceCtx, {
            type: 'bar',
            data: {
                labels: ['1000000', '1000001', '1000002', '1000003', '1000004', '1000005', '1000006', '1000007', '1000008', '1000009'],
                datasets: [
                    {
                        label: '上架',
                        data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                        backgroundColor: 'rgba(75, 192, 192, 0.5)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    },
                    {
                        label: '下架',
                        data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                        backgroundColor: 'rgba(255, 99, 132, 0.5)',
                        borderColor: 'rgba(255, 99, 132, 1)',
                        borderWidth: 1
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: true
                    }
                },
                scales: {
                    x: {
                        title: {
                            display: true,
                            text: '货品号'
                        }
                    },
                    y: {
                        title: {
                            display: true,
                            text: 'Quantity'
                        },
                        ticks: {
                            min: 1,
                            max: 5
                        }
                    }
                }
            }
        });

        async function updateChartData4() {
            try {
                const response = await fetch('http://localhost:5000/get_data4');
                const data = await response.json();
                const upValues = courseAttendanceChart.data.datasets[0].data.slice();
                const downValues = courseAttendanceChart.data.datasets[1].data.slice();

                data.forEach(item => {
                    const productIndex = courseAttendanceChart.data.labels.indexOf(item.productId);
                    if (productIndex!== -1) {
                        if (item.operation === 'U') {
                            upValues[productIndex] += item.quantity;
                        } else if (item.operation === 'D') {
                            downValues[productIndex] += item.quantity;
                        }
                    }
                });

                courseAttendanceChart.data.datasets[0].data = upValues;
                courseAttendanceChart.data.datasets[1].data = downValues;
                courseAttendanceChart.update();
            } catch (error) {
                console.error('Error fetching or updating chart data:', error);
            }
        }

        setInterval(updateChartData4, 5000);
        updateChartData4();

    // ----------------------5.classAttendance----------------

      const chartInstances = {}; // 存储图表实例
        const productIds = ['1000000', '1000001', '1000002', '1000003', '1000004', '1000005', '1000006', '1000007', '1000008', '1000009'];
        let isUpdating = false;

        // 生成指定透明度的随机颜色函数
        function generateRandomColor(alpha = 0.5) {
            const r = Math.floor(Math.random() * 255);
            const g = Math.floor(Math.random() * 255);
            const b = Math.floor(Math.random() * 255);
            return `rgba(${r}, ${g}, ${b}, ${alpha})`;
        }

        // 初始化图表函数
        function initializeCharts(productIds) {
            const chartsContainer = document.getElementById('charts-container');
            chartsContainer.innerHTML = ''; // 清空旧图表

            productIds.forEach(productId => {
                ['U', 'D'].forEach(operation => {
                    const container = document.createElement('div');
                    container.className = 'chart-container';

                    const title = document.createElement('h3');
                    title.innerText = `Product ID: ${productId} - Operation: ${operation}`;
                    container.appendChild(title);

                    const canvas = document.createElement('canvas');
                    canvas.id = `productChart_${productId}_${operation}`;
                    container.appendChild(canvas);

                    chartsContainer.appendChild(container);

                    // 初始化图表实例
                    const ctx = canvas.getContext('2d');
                    chartInstances[`${productId}-${operation}`] = new Chart(ctx, {
                        type: 'pie',
                        data: {
                            labels: ['product0', 'product1', 'product2', 'product3', 'product4', 'product5', 'product6', 'product7', 'product8', 'product9'],
                            datasets: [
                                {
                                    label: `Product ${operation}`,
                                    data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    backgroundColor: [],
                                    borderColor: [],
                                    borderWidth: 1
                                }
                            ]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    display: true
                                }
                            }
                        }
                    });
                });
            });
        }

        // 更新图表数据函数
        async function updateChartData() {
            if (isUpdating) return;
            isUpdating = true;

            try {
                const response = await fetch('http://localhost:5000/get_data5');
                const data = await response.json();
                productIds.forEach(productId => {
                    ['U', 'D'].forEach(operation => {
                        const productData = data.filter(item => item.productId === productId && item.operation === operation);
                        if (productData.length === 0) return;

                        const chart = chartInstances[`${productId}-${operation}`];
                        const quantityData = new Array(10).fill(0);

                        productData.forEach(item => {
                            const productNameIndex = parseInt(item.productName.slice(-1));
                            quantityData[productNameIndex] += item.quantity;
                        });

                        const backgroundColor = [];
                        const borderColor = [];

                        for (let i = 0; i < 10; i++) {
                            backgroundColor.push(generateRandomColor());
                            borderColor.push(generateRandomColor(1));
                        }

                        chart.data.datasets[0].data = quantityData;
                        chart.data.datasets[0].backgroundColor = backgroundColor;
                        chart.data.datasets[0].borderColor = borderColor;
                        chart.update();
                    });
                });
            } catch (error) {
                console.error('Error updating chart data:', error);
            } finally {
                isUpdating = false;
            }
        }

        // 初始化图表并定期更新数据
        initializeCharts(productIds);
        setInterval(updateChartData, 5000); // 每5秒更新一次
        updateChartData(); // 初始化立即更新
</script>
</body>
</html>